layui.define("jquery",function(exports){ //提示：模块也可以依赖其它模块，如：layui.define('layer', callback);

    var $ = layui.jquery;

    $(document).ajaxComplete(function(event,obj,settings){
        if (obj.responseText == 'timeout') { //超时标识
            // location.href='login'; //跳转到登录页面
            window.top.location.href="/fsm/loginPage";
        }
    });

    function Set() {
        this.values = {};//集合数据保存对象的属性值
        this.length = 0; //集合中值的个数
        this.add.apply(this, arguments);//把所有的参数添加到集合
    };
    //集合中添加元素
    Set.prototype.add = function () {
        for (var i = 0, len = arguments.length; i < len; i++) {
            var val = arguments[i];
            var str = Set._valToStr(val);//转换为字符串
            if (!this.values.hasOwnProperty(str)) { //如果不在集合中,将字符串和值对应起来,集合中的长度+1
                this.values[str] = val;
                this.length++;
            }
        }
    };
    //获取值
    Set.prototype.get = function (index) {
        if (isNaN(parseFloat(index)) || !isFinite(index) || index >= this.length)
            return undefined;
        for (var s in this.values) { //集合中所有的字符串
            if (this.values.hasOwnProperty(s)) {
                if (index == 0)
                    return this.values[s];
                index--;
            }
        }
        return this;//支持链式调用
    };
    //集合中删除元素
    Set.prototype.remove = function () {
        for (var i = 0, len = arguments.length ; i < len; i++) {
            var str = Set._valToStr(arguments[i]);
            if (this.values.hasOwnProperty(str)) {
                delete this.values[str];
                this.length--;
            }
        }
        return this;//返回this为了支持链式调用
    };
//是否包含某个值
    Set.prototype.contains = function (value) {
        return this.values.hasOwnProperty(Set._valToStr(value));
    };
    //返回集合的长度
    Set.prototype.size = function () {
        return this.length;
    };
//在指定的上下文遍历集合中的所有元素
    Set.prototype.foreach = function (f, context) {
        for (var s in this.values) { //集合中所有的字符串
            if (this.values.hasOwnProperty(s)) { //去掉继承而来的属性
                f.call(context, this.values[s]);
            }
        }
    };
    //比较两个Set是否相等
    Set.prototype.equals = function (that) {
        if (this == that)
            return true;
//如果that 对象不是一个集合,它和this不相等,使用instanceof 使这个方法可以应用于Set的任何子类
//注意null和undefined两个值是无法用于instanceof 运算的
        if (!(that instanceof Set))
            return false;
        if (this.size() != that.size())
            return false;
        try {
            this.foreach(function (v) { if (!(that.contains(v))) throw false; });
        }
        catch (e) {
            if (e === false)
                return false;
            throw e;
        }
    };
    Set._valToStr = function (value) {
        switch (value) {
            case undefined:
                return "undefined";
            case null:
                return "null";
            case true:
                return "true";
            case false:
                return "false";
            default:
                switch (typeof value) {
                    case "number": //数字带有number前缀
                        return "number" + value;
                    case "string"://字符串带有string前缀
                        return "string" + value;
                    default:
                        return "@" + objectId(value);
                }
        }
    }
        var commonObj = {

        currentData:null,
        maps:{},
        codeDetail:{},
        intiTableColorChange:function(data){
            // $(".layui-table-box tr").click(function(e){
            //     // $(".layui-table-box  tr").removeClass("active");
            //     $(".layui-table-box  tr").css("background","");
            //     // $(this).addClass("active");
            //     $(this).css("background","#dacdcd");
            // });
        },
        /*必须使用实体类字段名注册*/
        regMap:function (key,mapObj) {
            this.maps[key] = mapObj;

        },
        getMap:function (key) {
            return this.maps[key];
        },
        rmMap:function (key) {
            this.maps.remove(key);
        },
        getRequestParam : function (name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location;
            r = r.search;
            r = r.substr(1);
            r = r.match(reg);
            if (r != null)
                return unescape(r[2]);
            return null;
        },

        getKeyValueFieldDesc:function (keyValueField) {

            if(keyValueField == null)
                return "";

            return keyValueField.value;
        },
        getMapValue:function(map,desc) {

            if(this.isNullString(map) ||this.isNullString(desc))
                return "";

            for(var key in map){

                if(map[key] == desc)
                    return key;
            }
            return "";
        },
        entityAddListObjField:function (entityJsonObj,listObjFieldName,listObjArray) {

            if(listObjArray.length!=0&&listObjArray!=undefined){

                for(var i=0;i<listObjArray.length;i++){

                    var oneObj = listObjArray[i];

                    for(var _fieldName in oneObj) {

                        var _value = oneObj[_fieldName];

                        console.log("entityAddListObjField:field:" + _fieldName + " value:" + _value);

                        entityJsonObj[listObjFieldName+"[" + i + "]." +_fieldName] = _value;
                    }
                }
            }

        },
        /*
        * 根据实体类字段填充表单
        * */
        setFormVal:function(formJsonData) {

            for(var _fieldName in formJsonData){

                var _value = formJsonData[_fieldName];

                console.log("field:"+_fieldName+" value:"+_value);

                if(this.isNullString(_value)) {
                    continue;
                }

                var htmlTag = $("[name='"+_fieldName+"']");

                var htmlType = htmlTag.attr("type");

                if(this.isNullString(htmlType)){
                    continue;
                }

                switch (htmlType){
                    case 'text':
                    case 'textarea':
                    case 'hidden':
                    case 'button':
                        $("[name='" + _fieldName + "']").val(_value);
                        break;
                    case 'select-one':
                        this.setSelectValue("select[name="+_fieldName+"]",_fieldName,_value);
                        break;
                    case 'radio':
                        this.setRadioValue("input[type='radio'][name='"+_fieldName+"']",_value);
                        break;
                    case 'checkbox':
                        this.setCheckboxValue("input[type='checkbox'][name='"+_fieldName+"']",_value);
                        break;
                    default:
                        break;
                }
            }

        },

        isNullString:function(_value){

            if(_value == "" || _value == null || _value == undefined || _value == 'undefined') {
                return true;
            }

            return false;
        },
        /*
        根据枚举描述来选中select
        * @param: jquery 选择器
        * @param: 描述
        * */
        setSelectValue:function (_selector,_field,_fieldValue) {

            var map = this.getMap(_field);

            $(_selector).val(this.getMapValue(map,_fieldValue));
        },
        /*
        根据枚举描述来选中radio
        * @param: jquery 选择器
        * @param: 描述
        * */
        setRadioValue:function (_selector,_fieldValue) {

            $(_selector).each(function () {
                if($(this).attr("title") == _fieldValue)
                    $(this).attr("checked",true);
            });

        },
        /*
        根据枚举描述来选中radio
        * @param: jquery 选择器
        * @param: 描述
        * */
        setCheckboxValue:function (_selector,_fieldValue) {

            $(_selector).each(function () {
                if($(this).attr("title") == _fieldValue)
                    $(this).attr("checked",true);
            });
        },

        getFormData:function (formId) {

            var d = {};
            var t = $("#"+formId).serializeArray();

            $.each(t, function() {
                d[this.name] = this.value;
            });

            return d;
        },
        getFormData2:function (jqueryObj) {

            var obj = {};
            var t = jqueryObj.serializeArray();

            $.each(t, function() {

                var _fieldVal = obj[this.name];

                if (_fieldVal == undefined) {//当前字段未重复出现
                    obj[this.name] = this.value;
                } else {

                    if (!(_fieldVal instanceof Array)) {
                        var ar = new Array();
                        ar[0] = _fieldVal;//first value
                        ar[1] = this.value;
                        obj[this.name] = ar.join(",");
                    } else {
                        var currentLength = _fieldVal.length;
                        _fieldVal[currentLength] = this.value;
                        obj[this.name] = _fieldVal;
                    }
                }
            });

            return obj;
        },
        openTab:function(url,icon,title){
            var htm = '<a href="javascript:;" data-url="'+url+'"><i class="'+icon+'" ></i><cite>'+title+'</cite></a>';
            parent.addTab($(htm))
        },
        showBoolean: function(boolean){

            if(boolean==true||boolean==1){
                return "<input type='checkbox'checked='' lay-skin='switch' lay-text='是|否' disabled>";
            }else{
                return "<input type='checkbox'lay-skin='switch' lay-text='是|否' disabled>";
            }

        },
        getCodeNames:function (arrayObj,type) {//获取key:value中的codeDesc
            var codeDesc = [];
            if(arrayObj!=undefined&&arrayObj.length!=0){
                if(type==1||type==2){//key:value格式
                    for(var i=0;i<arrayObj.length;i++){
                        if(arrayObj[i]!=null&&arrayObj[i]!=undefined){
                            codeDesc.push(arrayObj[i].value);
                        }
                    }
                }else{//多选框字符串格式
                    for(var i=0;i<arrayObj.length;i++){
                        codeDesc.push(arrayObj[i]);
                    }
                }
            }
            return codeDesc.join(',');

        },
        showArrayDesc:function (arrayObj,showField) {//拼接数组某字段内容

            if(arrayObj==undefined || arrayObj.length==0){
                return "";
            }

            var desc = [];

            for(var i=0;i<arrayObj.length;i++){
                desc.push(arrayObj[i][showField])
            }

            return desc.join(',');

        },
        /*把对象数组中的某个值全部拿出来转换成字符串并去重*/
        arrayObjToString:function (arrayObj,name,type) {
            var s = new Set();
            if (arrayObj != null && arrayObj.length != 0) {
                for (var i = 0; i < arrayObj.length; i++) {
                    if (type == "5") {//价格预算
                        if("purchase"==name){
                            if (arrayObj[i]['moneyLow'] != null) {
                                s.add(arrayObj[i]['moneyLow']);
                            }
                            if (arrayObj[i]['moneyHigh'] != null) {
                                s.add(arrayObj[i]['moneyHigh']);
                            }
                        }else if("rent"==name){
                            if (arrayObj[i]['rentMoneyLow'] != null) {
                                s.add(arrayObj[i]['rentMoneyLow']);
                            }
                            if (arrayObj[i]['rentMoneyHigh'] != null) {
                                s.add(arrayObj[i]['rentMoneyHigh']);
                            }
                        }
                    } else {
                        var obj = arrayObj[i][name];
                        if (type == '1') {//表示是基本类型
                            s.add(obj);
                        } else if (type == "2") {//表示是key:value类型
                            s.add(obj.value);
                        } else {//表示是一个数组
                            if (obj != null && obj.length != 0) {
                                for (var v = 0; v < obj.length; v++) {
                                    if (type == "3") {//表示数组是基本类型
                                        s.add(obj[v]);
                                    } else if (type == "4") {//表示数组是key:value类型
                                        s.add(obj[v].value);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            var array = [];
            for(var a=0;a<s.size();a++){
                array.push(s.get(a));
            }
            if (type == "5") {//价格预算会有多条数据，取这多条数据的最大值和最小值
                function sortNumber(a, b) {
                    return a - b
                }
                array.sort(sortNumber);
                if (array.length != 0) {
                    if("rent"==name){
                        if (array.length == 1)
                            return array[0] + "元左右"
                        else
                            return array[0] + "-" + array[array.length - 1] + "元"
                    }else {
                        if (array.length == 1)
                            return array[0] + "万左右"
                        else
                            return array[0] + "-" + array[array.length - 1] + "万"
                    }
                }
            }
            return array.join(",");
        },
        /*拼接数据的范围*/
        rangeString:function(minValue,maxValue,unit){
            if(minValue==null||minValue==""){
                minValue = 0
            };
            if(maxValue==null||maxValue==""){
                maxValue = 0
            };
            if(minValue==0&&maxValue==0){
                return "";
            }else if(minValue==0&&maxValue>0){
                return maxValue+unit;
            }else if(minValue>0&&maxValue==0){
                return minValue+unit;
            }else{
                return minValue+unit+'-'+maxValue+unit;
            }
        },
        cssTitleCenter:function (id) {//多选框label文字居中
            if(id!=undefined&&id.trim().length!=0){
                var _this = $("#"+id+" .zdy-line-height");
                var h =_this[0].offsetHeight;
                _this.css({"padding":"0px 0px","line-height":h+"px"});
            }else{
                $(".zdy-line-height").each(function () {
                    var _this = $(this);
                    var h =_this.context.offsetHeight;
                    _this.css({"padding":"0px 0px","line-height":h+"px"});
                })
            }
        },
        /**
         * 下拉框搜索事件查询数据
         * <div class="layui-inline">
            <label class="layui-form-label"></label>
            <div class="layui-input-inline layui-form" id="divId" >
            <select>
            <option value="">请搜索</option>
            </select>
            </div>
           </div>
         * @param divId
         * @param dataName 接收参数名称
         * @param url 接收地址
         * @param document
         * @param form layui的form对象
         * @param callback 请求返回数据的回调方法
         */
        selectKeyup:function(divId,dataName,url,document,form,callback){
            $('#'+divId).find('input').removeAttr("readonly");//把抛客人员修改成能编辑
            var time;
            $(document).on("keyup","#"+divId+" input",function(){
                var value = $(this).val();
                clearTimeout(time);
                time = setTimeout(function() {
                    console.log(value);
                    if (value != "" && value.trim().length != 0) {
                        var json = {};
                        json[dataName] = value;
                        $.ajax({
                            type: "post",
                            async: false,
                            data: json,
                            url: url,
                            dataType: "json",
                            success: function (data) {
                                if (data != null && data.length != 0) {
                                    setTimeout(function () {
                                        var html = callback(data);
                                        $("#" + divId + " > select").html(html);
                                        form.render("select", $('#'+divId).attr('lay-filter'));
                                        $('#' + divId).find('input').removeAttr("readonly");
                                        var input = $('select[name="' + divId + '"]').next().find('.layui-select-title input');
                                        input.val(value);
                                        input.focus();
                                        input.click();//展开下拉
                                    }, 210)
                                }
                            },
                            error: function () {
                                layer.msg("操作异常");
                            }
                        });
                    }
                },700);
            });
        },
        intTableColorChange:function(){//表格每一行点击颜色变化表示选中
        $(".layui-table-box tr").click(function(e){
            $(".layui-table-box  tr ").css("background","");
            $(this).css("background","#dacdcd");
        });
        },
        copyObject:function (obj) {//对象copy
            if(obj === null) return null
            if(typeof obj !== 'object') return obj;
            if(obj.constructor===Date) return new Date(obj);
            if(obj.constructor === RegExp) return new RegExp(obj);
            var newObj = new obj.constructor ();  //保持继承链
            for (var key in obj) {
                if (obj.hasOwnProperty(key)) {   //不遍历其原型链上的属性
                    var val = obj[key];
                    newObj[key] = typeof val === 'object' ? arguments.callee(val) : val; // 使用arguments.callee解除与函数名的耦合
                }
            }
            return newObj;
        },
        addCustomer:function (layer,callback) {//新增客户弹框
            var but = 0;
            layer.open({
                type: 2
                , title: '添加客户'
                , area: ['99%', '99%']
                ,shade:[0.3, '#000']
                , content: ['/fsm/page/editCustomer?linkSource=crm'] //no表示没有滚动条模式
                //, btn: ['保存', '退出']
                , success: function (layero,index) {

                }
                /*,yes:function(index,layero){//该回调携带两个参数，分别为当前层索引、当前层DOM对象
                    but = 1;
                    var body = layer.getChildFrame('body', index); //得到子页面层的BODY
                    var button = body.find('[lay-submit]'); //获取子窗口表单提交按钮dom
                    button.click();
                },
                btn2: function (index,layero) {
                    layer.close(index);
                    console.log("退出"+index);
                },
                end: function() {//删除弹框时重新加载数据表格
                    callback();
                }*/
                , zIndex: layer.zIndex //重点1

            });
        },getZyUser:function (zyUserId) {
            var zyUser = "";
                $.ajax({
                    type : "post",
                    async: false,
                    data: {zyUserId:zyUserId},
                    url : "/fsm/customer/getZyUserId",
                    dataType : "json",
                    success : function(data) {
                        zyUser = data;
                    },
                    error:function(){
                        layer.msg("操作异常");
                    }
                });
                return zyUser;
            }

    };

    //输出接口
    exports('common', commonObj);
});



